package com.yuyu.shop.domain.order.service;

import com.aliyun.openservices.ons.api.*;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.yuyu.commons.constant.AliMqPropertiesConstant;
import com.yuyu.commons.constant.BaseConstant;
import com.yuyu.commons.exception.BusinessException;
import com.yuyu.commons.mq.ons.OnsProducer;
import com.yuyu.commons.security.LoginContext;
import com.yuyu.commons.security.LoginUser;
import com.yuyu.shop.api.apimodel.order.dto.OrderCreateDTO;
import com.yuyu.shop.api.apimodel.order.dto.SecKillReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author
 * @version 1.0
 * @description: TODO
 * @date 2022/8/30 11:13
 */
@Service
@Slf4j
public class SecKillService {

    @Resource
    private ProducerBean producerBean;

    /**
     *
     * @param req
     */
    public void secKill( SecKillReq req){
        LoginUser user = LoginContext.getUser();
        if (Objects.isNull(user) || Objects.isNull(user.getUserId()) ){
            throw new BusinessException("秒杀失败,用户信息缺失!");
        }
        //检查库存
//        Boolean isEnough = stockCache.decrStock(req.getGoodsId(), Long.valueOf(BaseConstant.ONE));
//        if (!isEnough){
//            throw new BusinessException("秒杀失败,库存不足!");
//        }
        //construct orderCreateDto
        OrderCreateDTO orderCreateDTO = new OrderCreateDTO();
        orderCreateDTO.setOrderType(BaseConstant.ONE)
                .setGoodsId(req.getGoodsId())
                .setGoodsNum(BaseConstant.ONE)
                .setShopId(req.getShopId())
                .setUserId(user.getUserId());
        Message message = new Message();
        String s = JSON.toJSON(orderCreateDTO).toString();
        message.setTopic(AliMqPropertiesConstant.secKillOrderTopic);
        message.setTag(AliMqPropertiesConstant.secKillTag);
        message.setBody(s.getBytes(StandardCharsets.UTF_8));
        producerBean.sendAsync(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                //todo
                log.info("success");

            }

            @Override
            public void onException(OnExceptionContext onExceptionContext) {
                //todo
                log.error("failed");
            }
        });
    }


}
